#!/usr/bin/env python3
"""
Show detailed information of a node with code from the graph
"""

import pickle
import json

# Load the modified graph with code_content
pkl_file = "/data_ext/ref_code/LocAgent/index_data_strict/pp_data/graph_index_v2.3/business-payout-with-code-content.pkl"

print("Loading graph...")
with open(pkl_file, "rb") as f:
    G = pickle.load(f)

print(f"Graph loaded: {G.number_of_nodes()} nodes\n")

# Find different types of nodes with code
examples = {
    'function': None,
    'class': None,
    'file': None
}

for node_id in G.nodes():
    node_data = G.nodes[node_id]
    node_type = node_data.get('type')

    # Skip if no code or already found this type
    if not node_data.get('code') or node_type not in examples or examples[node_type]:
        continue

    # Store example if it's a reasonable size
    if len(node_data['code']) < 2000:  # Not too long
        examples[node_type] = (node_id, node_data)

    # Stop when we have all types
    if all(examples.values()):
        break

# Display detailed information for each type
for node_type, example in examples.items():
    if not example:
        continue

    node_id, node_data = example

    print("=" * 80)
    print(f"NODE TYPE: {node_type.upper()}")
    print("=" * 80)
    print(f"\n📍 Node ID: {node_id}")
    print(f"\n📊 Node Attributes:")

    for key, value in sorted(node_data.items()):
        if key in ['code', 'code_content']:
            # Show code statistics
            if value:
                lines = value.split('\n')
                print(f"  • {key}: {len(lines)} lines, {len(value)} characters")
            else:
                print(f"  • {key}: None/Empty")
        elif isinstance(value, str):
            if len(value) > 100:
                print(f"  • {key}: (string, {len(value)} chars)")
            else:
                print(f"  • {key}: {repr(value)}")
        elif isinstance(value, (list, dict)):
            print(f"  • {key}: {type(value).__name__} with {len(value)} items")
            if len(value) > 0 and key == 'method_calls':
                # Show method calls if present
                for i, item in enumerate(value[:3]):
                    print(f"      [{i}]: {item}")
                if len(value) > 3:
                    print(f"      ... and {len(value)-3} more")
        else:
            print(f"  • {key}: {value}")

    # Show the actual code
    print(f"\n📝 Code Content ({key}):")
    print("-" * 40)
    code = node_data.get('code', '')
    if code:
        lines = code.split('\n')
        # Show first 20 lines
        for i, line in enumerate(lines[:20], 1):
            print(f"{i:4} | {line}")
        if len(lines) > 20:
            print(f"     | ... ({len(lines) - 20} more lines)")
    print("-" * 40)

    # Verify code and code_content are the same
    if 'code' in node_data and 'code_content' in node_data:
        if node_data['code'] == node_data['code_content']:
            print("✅ Verified: 'code' and 'code_content' are identical")
        else:
            print("⚠️ Warning: 'code' and 'code_content' differ!")

    print()

# Also show a specific interesting node if we can find one
print("\n" + "=" * 80)
print("LOOKING FOR A SPECIFIC INTERESTING NODE")
print("=" * 80)

# Try to find a node with interesting relationships
target_node = None
for node_id in G.nodes():
    node_data = G.nodes[node_id]
    # Look for a function with method calls
    if (node_data.get('type') == 'function' and
        node_data.get('method_calls') and
        len(node_data.get('method_calls', [])) > 2):
        target_node = (node_id, node_data)
        break

if target_node:
    node_id, node_data = target_node
    print(f"\n📍 Found interesting function: {node_id}")
    print(f"   Type: {node_data.get('type')}")
    print(f"   Method calls: {len(node_data.get('method_calls', []))} calls")
    print(f"   Code size: {len(node_data.get('code', ''))} chars")

    # Show its relationships
    print(f"\n🔗 Graph Relationships:")

    # Incoming edges
    in_edges = list(G.in_edges(node_id, data=True))
    print(f"   Incoming edges: {len(in_edges)}")
    for src, dst, data in in_edges[:3]:
        edge_type = data.get('type', 'unknown')
        print(f"     ← {src} [{edge_type}]")

    # Outgoing edges
    out_edges = list(G.out_edges(node_id, data=True))
    print(f"   Outgoing edges: {len(out_edges)}")
    for src, dst, data in out_edges[:3]:
        edge_type = data.get('type', 'unknown')
        print(f"     → {dst} [{edge_type}]")

print("\n✅ Analysis complete!")